<template>
  <div class="demo">
    <div class="demo-title">加载更多</div>
    <div class="demo-content">
      <List
        class="demo-loadmore-list"
        :loading="initLoading"
        item-layout="horizontal"
        :data-source="list"
      >
        <template #loadMore>
          <div
            v-if="!initLoading && !loading"
            :style="{ textAlign: 'center', marginTop: '12px', height: '32px', lineHeight: '32px' }"
          >
            <Button @click="onLoadMore">loading more</Button>
          </div>
        </template>
        <template #renderItem="{ item }">
          <List.Item>
            <template #actions>
              <a key="list-loadmore-edit">edit</a>
              <a key="list-loadmore-more">more</a>
            </template>
            <Skeleton avatar :title="false" :loading="!!item.loading" active>
              <List.Item.Meta :description="description">
                <template #title>
                  <a :href="link">{{ item.name.last }}</a>
                </template>
                <template #avatar>
                  <Avatar :src="item.picture.large" />
                </template>
              </List.Item.Meta>
              <div>content</div>
            </Skeleton>
          </List.Item>
        </template>
      </List>
    </div>
  </div>
</template>

<script lang="ts" setup>
  import { onMounted, ref, nextTick } from 'vue';
  import Avatar from '@sscd/avatar';
  import Button from '@sscd/button';
  import Skeleton from '@sscd/skeleton';
  import List from '@sscd/list';
  const count = 3;
  const fakeDataUrl = `https://randomuser.me/api/?results=${count}&inc=name,gender,email,nat,picture&noinfo`;
  const description =
    'SSC+ Design, a design language for background applications, is refined by SSC+ UED Team';
  const link = 'https://www.antdv.com/';
  const initLoading = ref(true);
  const loading = ref(false);
  const data = ref([]);
  const list = ref([]);
  onMounted(() => {
    fetch(fakeDataUrl)
      .then((res) => res.json())
      .then((res) => {
        initLoading.value = false;
        data.value = res.results;
        list.value = res.results;
      });
  });
  const onLoadMore = () => {
    loading.value = true;
    list.value = data.value.concat(
      [...new Array(count)].map(() => ({ loading: true, name: {}, picture: {} }))
    );
    fetch(fakeDataUrl)
      .then((res) => res.json())
      .then((res) => {
        const newData = data.value.concat(res.results);
        loading.value = false;
        data.value = newData;
        list.value = newData;
        nextTick(() => {
          // Resetting window's offsetTop so as to display react-virtualized demo underfloor.
          // In real scene, you can using public method of react-virtualized:
          // https://stackoverflow.com/questions/46700726/how-to-use-public-method-updateposition-of-react-virtualized
          window.dispatchEvent(new Event('resize'));
        });
      });
  };
</script>
